from __future__ import absolute_import
import logging
import re
import traceback
import pymysql
from obs import ObsClient
from conf.conf import (ObsAK, ObsEndpoint, ObsSK, BucketName, DBName,
                       DBHost, DBPort, DBUser, DBPassword)
obs_client = ObsClient(access_key_id=ObsAK,
                       secret_access_key=ObsSK, server=ObsEndpoint)

mysql_db = pymysql.connect(host=DBHost, port=DBPort, user=DBUser, password=DBPassword, database=DBName)

logger = logging.getLogger(__name__)


def delete_test_data(file_path):
    cursor = mysql_db.cursor()
    file_list = []
    with open(file_path, 'r+', encoding='utf-8') as file:
        for _, line in enumerate(file):
            line = line.strip('\n')
            file_list.append(line)
        file.truncate(0)
    for file in file_list:
        resp = obs_client.deleteObject(BucketName, file)
        if resp.status >= 300:
            logger.error("删除obs数据%s失败%s", file, resp.errorCode)
        if re.search(r'anonymize', file):
            sql = "DELETE FROM data_mgt_anonymizeddata WHERE object_key = %s"
        elif re.search(r'scene', file):
            file = file.rsplit('/', 1)[0]
            sql = "DELETE FROM data_mgt_scenedata WHERE object_key = %s"
        elif re.search(r'original', file):
            sql = "DELETE FROM data_mgt_originaldata WHERE object_key = %s"
        else:
            return
        try:
            cursor.execute(sql, file)
            mysql_db.commit()
        except Exception as e:
            logger.error("删除db数据失败：%s, %s", repr(e), traceback.format_exc())
            mysql_db.rollback()


if __name__ == '__main__':
    delete_test_data("./conf/init_log.txt")
